package com.kchouse.homepage;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.BannerItem;
import com.kchouse.bean.HostItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.bean.PrestoreItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.myadapter.PrestoreAdapter;
import com.kchouse.union.MerchantDetailsActivity;
import com.kchouse.view.ProgressView;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;

public class PrestoreActivity extends BaseActivity implements View.OnClickListener {

    private PrestoreActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private HaoRecyclerView hao_recycleview;
    private PrestoreAdapter prestoreAdapter;
    private ArrayList<PrestoreItem> listprestore = new ArrayList<>();
    private int page = 1;
    private int totalCount;//总个数
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prestore);

        mContent = this;
        addAct(mContent);

        intiData();
        intiView();
    }

    private void intiData() {

        intent=getIntent();
        GetPrestoreList(page);
    }

    /**
     * 获取预存活动列表
     */
    private void GetPrestoreList(int page) {
        String url = API.GetPrestoreList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listprestore.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                    } else {
                        listprestore.addAll(JSONObject.parseArray(data.getString("prestoreList"), PrestoreItem.class));
                        prestoreAdapter.notifyDataSetChanged();
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }




    private void intiView() {

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("预存活动");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);


        hao_recycleview = (HaoRecyclerView) findViewById(R.id.hao_recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContent);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hao_recycleview.setLayoutManager(layoutManager);
        //添加Android自带的分割线
//        hao_recycleview.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

        //设置自定义加载中和到底了效果
        ProgressView progressView = new ProgressView(mContent);
        progressView.setIndicatorId(ProgressView.BallPulse);
        progressView.setIndicatorColor(0xff69b3e0);
        hao_recycleview.setFootLoadingView(progressView);

        prestoreAdapter = new PrestoreAdapter(mContent, listprestore);
        hao_recycleview.setAdapter(prestoreAdapter);
        hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PrestoreItem item = listprestore.get(position);
//                        ToastUtils.getInstanc(getActivity()).showToast("商家id："+item.getId());
                intent.putExtra("prestoreId", item.getId());
                intent.setClass(mContent, PrestoreDetailsActivity.class);
                startActivity(intent);
            }
        });
        hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        page = page + 1;
                        GetPrestoreList(page);
                        hao_recycleview.loadMoreComplete();

                    }
                }, 2000);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                delAct(mContent);
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            delAct(mContent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
